<?php


namespace app\index\controller;
use think\Controller;

class personal extends Controller
{
    /**
     * 个人中心首页
     */
    public function index(){
        $id = $this->is_login();
        $data = Db('user')->where(['id'=>$id])->find();
        $this->assign('data',$data);
        return view('personal/personcenter');
        // return $this->fetch('personcenter');
    }

    /**
     * 确保用户已登录
     */
    public function is_login(){
        $id = session('user.id');
        if(empty($id)){
            return $this->redirect('index/login');
        }
        return $id;
    }


    /**
     * 修改
     */
    public function edit(){
        $id = $this->is_login();
        if(request()->isPost()){
            $post = input('param.');
            $key = $post['key'];
            if(empty($post['value'])){
                $data = ['code'=>400,'msg'=>'表单不能为空'];
                return $data;
            }
            if($key == 'mob'){
                if(!preg_match('/^1[34578]\d{9}$/',$post['value'])){
                    return ['code'=>400,'message'=>'电话格式不对'];
                }
            }
            if($key == 'email'){
                if(!preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/',$post['value'])){
                        return ['code'=>400,'message'=>'邮箱格式不对'];
                    }
            }
            $return = Db('user')->where(['id'=>$id])->setField($key,$post['value']);
            if($return>0){
                $data = ['code'=>1,'msg'=>'修改成功'];
                return $data;
            }else{
                $data = ['code'=>400,'msg'=>'修改失败'];
                return $data;
            }
        }
    }









}